package management

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"reflect"
	"strconv"
	"time"

	"github.com/gorilla/mux"
	"github.com/jsrccb/nachuan/common"
	"github.com/tealeg/xlsx"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func initOrderApi(r *mux.Router) {

	s := r.PathPrefix("/order").Subrouter()
	// s.HandleFunc("/list", UserListHandler)
	s.HandleFunc("/updsave", handleOrderSave)
	s.HandleFunc("/savestep", handleOrderSaveStep)
	s.HandleFunc("/updStsById", handleUpdStsById)
	//请求/order/handleOrderqueryall?ordertype=xxx&skip=1&limit=1
	s.HandleFunc("/handleOrderqueryall", handleOrderqueryall)
	s.HandleFunc("/download", handleOrderdownload)
	s.HandleFunc("/del", handleOrderdel)
	s.HandleFunc("/operorderfloor", handleOperatingOrderFloor)
	s.HandleFunc("/operotherorderfloor", handleOperatingOtherOrderFloor)

	ents := r.PathPrefix("/orderevent").Subrouter()
	ents.HandleFunc("/queryall", handleOrderEventqueryall)
	ents.HandleFunc("/querybyorderno", handleOrderEventQuery)
	ents.HandleFunc("/save", handleOrderEventSave)
	ents.HandleFunc("/upd", handleOrderEventUpd)
	ents.HandleFunc("/savestep", handleOrderEventSaveStep)
	// ents.HandleFunc("/savetaxcancelstep", handleOrderCancelTaxSaveStep)
	ents.HandleFunc("/updstep", handleOrderEventUpdStep)
	ents.HandleFunc("/nextstep", handleOrderEventNextStep)

}

func handleOperatingOtherOrderFloor(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entcluests  string
		// custommgr string
		// rolelimit     *common.RoleLimits

		todayBGordercount   int64 //今日变更订单
		todayZXordercount   int64 //今日注销订单
		todaySBordercount   int64 //今日商标订单
		todayJZZZordercount int64 //今日建筑资质订单
		todayQTordercount   int64 //今日其他订单

		monBGordercount   int64 //本月变更订单
		monZXordercount   int64 //本月注销订单
		monSBordercount   int64 //本月商标订单
		monJZZZordercount int64 //本月建筑资质订单
		monQTordercount   int64 //本月其他订单

	)
	cluemap := make(map[string]interface{})
	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	// custommgr = req.PostForm.Get("custommgr")

	if todayBGordercount, err = G_OrderMgr.getOperatingOrderBGCount(); err != nil {
		goto ERR
	}
	if todayZXordercount, err = G_OrderMgr.getOperatingOrderZXCount(); err != nil {
		goto ERR
	}
	if todaySBordercount, err = G_OrderMgr.getOperatingOrderSBCount(); err != nil {
		goto ERR
	}
	if todayJZZZordercount, err = G_OrderMgr.getOperatingOrderJZZZCount(); err != nil {
		goto ERR
	}
	if todayQTordercount, err = G_OrderMgr.getOperatingOrderQTCount(); err != nil {
		goto ERR
	}
	if monBGordercount, err = G_OrderMgr.getOperatingOrderBGCountMon(); err != nil {
		goto ERR
	}
	if monZXordercount, err = G_OrderMgr.getOperatingOrderZXCountMon(); err != nil {
		goto ERR
	}
	if monSBordercount, err = G_OrderMgr.getOperatingOrderSBCountMon(); err != nil {
		goto ERR
	}
	if monJZZZordercount, err = G_OrderMgr.getOperatingOrderJZZZCountMon(); err != nil {
		goto ERR
	}
	if monQTordercount, err = G_OrderMgr.getOperatingOrderQTCountMon(); err != nil {
		goto ERR
	}

	cluemap["todayBGordercount"] = todayBGordercount
	cluemap["todayZXordercount"] = todayZXordercount
	cluemap["todaySBordercount"] = todaySBordercount
	cluemap["todayJZZZordercount"] = todayJZZZordercount
	cluemap["todayQTordercount"] = todayQTordercount
	cluemap["monBGordercount"] = monBGordercount
	cluemap["monZXordercount"] = monZXordercount
	cluemap["monSBordercount"] = monSBordercount
	cluemap["monJZZZordercount"] = monJZZZordercount
	cluemap["monQTordercount"] = monQTordercount

	if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

//今日变更订单
func (orderMgr *OrderMgr) getOperatingOrderBGCount() (doccount int64, err error) {

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), bson.M{"orderDate": bson.M{"$regex": common.BuildDateTodayStr2(), "$options": "$i"}, "orderType": "变更", "orderStatus": bson.M{"$ne": "已废弃"}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}

	return
}

//今日注销订单
func (orderMgr *OrderMgr) getOperatingOrderZXCount() (doccount int64, err error) {

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), bson.M{"orderDate": bson.M{"$regex": common.BuildDateTodayStr2(), "$options": "$i"}, "orderType": "注销", "orderStatus": bson.M{"$ne": "已废弃"}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}

	return
}

//今日商标订单
func (orderMgr *OrderMgr) getOperatingOrderSBCount() (doccount int64, err error) {

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), bson.M{"orderDate": bson.M{"$regex": common.BuildDateTodayStr2(), "$options": "$i"}, "orderType": "商标", "orderStatus": bson.M{"$ne": "已废弃"}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}

	return
}

//今日建筑资质订单
func (orderMgr *OrderMgr) getOperatingOrderJZZZCount() (doccount int64, err error) {

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), bson.M{"orderDate": bson.M{"$regex": common.BuildDateTodayStr2(), "$options": "$i"}, "orderType": "建筑资质", "orderStatus": bson.M{"$ne": "已废弃"}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}
	return
}

//今日其他订单
func (orderMgr *OrderMgr) getOperatingOrderQTCount() (doccount int64, err error) {

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), bson.M{"orderDate": bson.M{"$regex": common.BuildDateTodayStr2(), "$options": "$i"}, "orderType": "其他", "orderStatus": bson.M{"$ne": "已废弃"}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}

	return
}

//本月变更订单
func (orderMgr *OrderMgr) getOperatingOrderBGCountMon() (doccount int64, err error) {

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), bson.M{"orderDate": bson.M{"$regex": common.BuildDateMonStr2(), "$options": "$i"}, "orderType": "变更", "orderStatus": bson.M{"$ne": "已废弃"}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}

	return
}

//本月注销订单
func (orderMgr *OrderMgr) getOperatingOrderZXCountMon() (doccount int64, err error) {

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), bson.M{"orderDate": bson.M{"$regex": common.BuildDateMonStr2(), "$options": "$i"}, "orderType": "注销", "orderStatus": bson.M{"$ne": "已废弃"}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}

	return
}

//本月商标订单
func (orderMgr *OrderMgr) getOperatingOrderSBCountMon() (doccount int64, err error) {

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), bson.M{"orderDate": bson.M{"$regex": common.BuildDateMonStr2(), "$options": "$i"}, "orderType": "商标", "orderStatus": bson.M{"$ne": "已废弃"}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}

	return
}

//本月建筑资质订单
func (orderMgr *OrderMgr) getOperatingOrderJZZZCountMon() (doccount int64, err error) {

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), bson.M{"orderDate": bson.M{"$regex": common.BuildDateMonStr2(), "$options": "$i"}, "orderType": "建筑资质", "orderStatus": bson.M{"$ne": "已废弃"}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}
	return
}

//本月其他订单
func (orderMgr *OrderMgr) getOperatingOrderQTCountMon() (doccount int64, err error) {

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), bson.M{"orderDate": bson.M{"$regex": common.BuildDateMonStr2(), "$options": "$i"}, "orderType": "其他", "orderStatus": bson.M{"$ne": "已废弃"}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}

	return
}

func handleOperatingOrderFloor(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entcluests  string
		// custommgr string
		// rolelimit     *common.RoleLimits

		todayorderagentcount   int64 //今日注册代账
		todayordernoagentcount int64 //今日注册不代账
		todayorderincomecount  int64 //今日迁入
		monorderagentcount     int64 //本月注册代账
		monordernoagentcount   int64 //本月注册不代账
		monorderincomecount    int64 //本月迁入

	)
	cluemap := make(map[string]interface{})
	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	// custommgr = req.PostForm.Get("custommgr")

	if todayorderagentcount, err = G_OrderMgr.getOperatingOrderAgentCount(); err != nil {
		goto ERR
	}
	if todayordernoagentcount, err = G_OrderMgr.getOperatingOrderNoAgentCount(); err != nil {
		goto ERR
	}
	if todayorderincomecount, err = G_OrderMgr.getOperatingOrderIncomeCount(); err != nil {
		goto ERR
	}
	if monorderagentcount, err = G_OrderMgr.getOperatingOrderAgentMonCount(); err != nil {
		goto ERR
	}
	if monordernoagentcount, err = G_OrderMgr.getOperatingOrderNoAgentMonCount(); err != nil {
		goto ERR
	}
	if monorderincomecount, err = G_OrderMgr.getOperatingOrderIncomeMonCount(); err != nil {
		goto ERR
	}

	cluemap["todayorderagentcount"] = todayorderagentcount
	cluemap["todayordernoagentcount"] = todayordernoagentcount
	cluemap["todayorderincomecount"] = todayorderincomecount
	cluemap["monorderagentcount"] = monorderagentcount
	cluemap["monordernoagentcount"] = monordernoagentcount
	cluemap["monorderincomecount"] = monorderincomecount

	if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

//今日注册代账
func (orderMgr *OrderMgr) getOperatingOrderAgentCount() (doccount int64, err error) {

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), bson.M{"orderDate": bson.M{"$regex": common.BuildDateTodayStr2(), "$options": "$i"}, "orderType": "注册", "agentAccount": "是", "orderStatus": bson.M{"$ne": "已废弃"}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}

	return
}

// 今日注册不代账
func (orderMgr *OrderMgr) getOperatingOrderNoAgentCount() (doccount int64, err error) {

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), bson.M{"orderDate": bson.M{"$regex": common.BuildDateTodayStr2(), "$options": "$i"}, "orderType": "注册", "agentAccount": "否", "orderStatus": bson.M{"$ne": "已废弃"}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}

	return
}

// 今日迁入
func (orderMgr *OrderMgr) getOperatingOrderIncomeCount() (doccount int64, err error) {

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), bson.M{"orderDate": bson.M{"$regex": common.BuildDateTodayStr2(), "$options": "$i"}, "orderType": "迁入", "orderStatus": bson.M{"$ne": "已废弃"}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}

	return
}

//本月注册代账
func (orderMgr *OrderMgr) getOperatingOrderAgentMonCount() (doccount int64, err error) {

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), bson.M{"orderDate": bson.M{"$regex": common.BuildDateMonStr2(), "$options": "$i"}, "orderType": "注册", "agentAccount": "是", "orderStatus": bson.M{"$ne": "已废弃"}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}

	return
}

// 本月注册不代账
func (orderMgr *OrderMgr) getOperatingOrderNoAgentMonCount() (doccount int64, err error) {

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), bson.M{"orderDate": bson.M{"$regex": common.BuildDateMonStr2(), "$options": "$i"}, "orderType": "注册", "agentAccount": "否", "orderStatus": bson.M{"$ne": "已废弃"}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}

	return
}

// 本月迁入
func (orderMgr *OrderMgr) getOperatingOrderIncomeMonCount() (doccount int64, err error) {

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), bson.M{"orderDate": bson.M{"$regex": common.BuildDateMonStr2(), "$options": "$i"}, "orderType": "迁入", "orderStatus": bson.M{"$ne": "已废弃"}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}

	return
}

type OrderMgr struct {
	client         *mongo.Client
	OrderColl      *mongo.Collection
	OrderEventColl *mongo.Collection
}

var (
	G_OrderMgr *OrderMgr
)

func (orderMgr *OrderMgr) getOrderEventCount(orderno string) (doccount int64, err error) {

	if doccount, err = orderMgr.OrderEventColl.CountDocuments(context.TODO(), bson.D{{"orderNo", orderno}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}
	return
}

func (orderMgr *OrderMgr) queryOrderEvent(orderno string, eventno string) (orderevent []*common.OrderEvent, err error) {

	var (
		cursor  *mongo.Cursor
		event   *common.OrderEvent
		findopt *options.FindOptions
		ctx     context.Context
	)

	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)
	findopt = &options.FindOptions{}
	if eventno == "" {
		cursor, err = orderMgr.OrderEventColl.Find(context.TODO(), bson.M{"orderNo": orderno}, findopt)
	} else {
		cursor, err = orderMgr.OrderEventColl.Find(context.TODO(), bson.M{"orderNo": orderno, "eventNo": eventno}, findopt)
	}

	defer cursor.Close(ctx)

	for cursor.Next(ctx) {
		event = &common.OrderEvent{}
		if err = cursor.Decode(event); err != nil {
			continue
		}
		orderevent = append(orderevent, event)
	}

	return
}

func (orderMgr *OrderMgr) updOrderEventStep(orderEvent *common.OrderEvent) (err error) {

	if orderEvent.OrderNo != "" && orderEvent.EventNo != "" {
		orderMgr.OrderEventColl.FindOneAndUpdate(context.TODO(), bson.M{"orderNo": orderEvent.OrderNo, "eventNo": orderEvent.EventNo}, bson.M{"$set": orderEvent})
	} else {
	}

	return
}

func (orderMgr *OrderMgr) updOrderEvent(orderEvent *common.OrderEvent) (err error) {

	if orderEvent.OrderNo != "" && orderEvent.EventNo != "" {
		orderMgr.OrderEventColl.FindOneAndUpdate(context.TODO(), bson.M{"orderNo": orderEvent.OrderNo, "eventNo": orderEvent.EventNo}, bson.M{"$set": orderEvent})
	} else {
		err = errors.New("OrderNo和EventNo不能为空")
	}

	return
}

func (orderMgr *OrderMgr) saveOrderEventStep(orderEvent *common.OrderEvent) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		evtcount int64
		// update *common.HostInfo
	)

	evtcount, _ = orderMgr.getOrderEventCount(orderEvent.OrderNo)
	orderEvent.CreateTime = common.BuildTimeNowStr()
	if evtcount == 0 {
		orderEvent.EventNo = "1"
		orderMgr.OrderEventColl.InsertOne(context.TODO(), orderEvent)
	} else {
		orderEvent.EventNo = string(evtcount + 1)
		orderMgr.OrderEventColl.InsertOne(context.TODO(), orderEvent)
	}

	return
}

func (orderMgr *OrderMgr) saveOrderEvent(orderEvent *common.OrderEvent) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		evtcount int64
		// update *common.HostInfo
	)

	evtcount, _ = orderMgr.getOrderEventCount(orderEvent.OrderNo)
	orderEvent.CreateTime = common.BuildTimeNowStr()
	if evtcount == 0 {
		orderEvent.EventNo = "1"
		orderMgr.OrderEventColl.InsertOne(context.TODO(), orderEvent)
	} else {
		orderEvent.EventNo = strconv.FormatInt(evtcount+1, 10)
		orderMgr.OrderEventColl.InsertOne(context.TODO(), orderEvent)
	}

	return
}

func handleOrderEventUpdStep(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte

		orderEvtStr  string
		orderevent   *common.OrderEvent
		order        *common.Order
		ordersts     string
		ordertyp     string
		ordernextsts string
		taxnextsts   string
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	orderEvtStr = req.PostForm.Get("ordereventinfo")

	if err = json.Unmarshal([]byte(orderEvtStr), &orderevent); err != nil {
		goto ERR
	}
	// fmt.Println(orderevent)

	order, _ = G_OrderMgr.getOrderbyNo(orderevent.OrderNo)

	if order == nil {
		if bytes, err = common.BuildResponse(-1, "error", "订单信息不存在"); err == nil {
			resp.Write(bytes)
		}
		return
	}

	// fmt.Println(order)
	ordersts = order.OrderStatus
	ordertyp = order.OrderType

	// fmt.Println(clueNo)
	if err = G_OrderMgr.updOrderEvent(orderevent); err == nil {

		if ordertyp == "注册" && orderevent.EventStatus == "已完成" && orderevent.OrderEventType == "流程任务" {
			ordernextsts = common.GetNextBussOrderSts(ordersts)
			G_OrderMgr.updOrderSts(orderevent.OrderNo, ordernextsts)
		}
		if ordertyp == "变更" && orderevent.EventStatus == "已完成" && orderevent.OrderEventType == "流程任务" {
			ordernextsts = common.GetNextChangeOrderSts(ordersts)
			G_OrderMgr.updOrderSts(orderevent.OrderNo, ordernextsts)
		}
		if ordertyp == "注销" && orderevent.EventStatus == "已完成" && orderevent.OrderEventType == "流程任务" {
			if orderevent.EventType2 == "税务注销" {
				taxnextsts = common.GetCANCELBUSTAXSTS(order.TaxStatus)
				G_OrderMgr.updTaxSts(orderevent.OrderNo, taxnextsts)
			} else {
				ordernextsts = common.GetNextCacncelBusOrderSts(ordersts)
				G_OrderMgr.updOrderSts(orderevent.OrderNo, ordernextsts)
			}
		}

		if bytes, err = common.BuildResponse(0, "success", orderevent); err == nil {
			resp.Write(bytes)
		}
	} else {
		if bytes, err = common.BuildResponse(-1, "error", "更新事件异常"); err == nil {
			resp.Write(bytes)
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleOrderEventNextStep(resp http.ResponseWriter, req *http.Request) {
	var (
		err          error
		bytes        []byte
		orderno      string
		order        *common.Order
		ordertyp     string
		ordersts     string
		ordernextsts string
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	orderno = req.PostForm.Get("orderno")

	order, err = G_OrderMgr.getOrderbyNo(orderno)
	// fmt.Println(clueNo)
	ordersts = order.OrderStatus
	ordertyp = order.OrderType

	if err != nil {
		goto ERR
	} else {
		if ordertyp == "注册" {
			ordernextsts = common.GetNextBussOrderSts(ordersts)
			// fmt.Println(orderno, ordernextsts)
			G_OrderMgr.updOrderSts(orderno, ordernextsts)
		}
		if ordertyp == "变更" {
			ordernextsts = common.GetNextChangeOrderSts(ordersts)
			// fmt.Println(orderno, ordernextsts)
			G_OrderMgr.updOrderSts(orderno, ordernextsts)
		}
		if ordertyp == "注销" {
			ordernextsts = common.GetNextCacncelBusOrderSts(ordersts)
			// fmt.Println(orderno, ordernextsts)
			G_OrderMgr.updOrderSts(orderno, ordernextsts)
		}
		if bytes, err = common.BuildResponse(0, "success", "订单更新成功"); err == nil {
			resp.Write(bytes)
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleOrderEventUpd(resp http.ResponseWriter, req *http.Request) {
	var (
		err         error
		bytes       []byte
		orderEvtStr string
		orderevent  *common.OrderEvent
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	orderEvtStr = req.PostForm.Get("ordereventinfo")

	if err = json.Unmarshal([]byte(orderEvtStr), &orderevent); err != nil {
		goto ERR
	}

	// fmt.Println(clueNo)
	if err = G_OrderMgr.updOrderEvent(orderevent); err == nil {
		if bytes, err = common.BuildResponse(0, "success", orderevent); err == nil {
			resp.Write(bytes)
		}
	} else {
		if bytes, err = common.BuildResponse(-1, "error", "更新事件异常"); err == nil {
			resp.Write(bytes)
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleOrderEventQuery(resp http.ResponseWriter, req *http.Request) {
	var (
		err         error
		bytes       []byte
		orderEvtStr string
		orderevent  []*common.OrderEvent
		orderno     string
		eventno     string

		// rolelimit     *common.RoleLimits
	)

	query := req.URL.Query()
	orderno = query.Get("orderno")
	eventno = query.Get("eventno")
	if orderno == "" {
		if bytes, err = common.BuildResponse(-1, "error", "订单号不能为空"); err == nil {
			resp.Write(bytes)
		}
		return
	}

	if err = json.Unmarshal([]byte(orderEvtStr), &orderevent); err != nil {
		goto ERR
	}
	// fmt.Println(clueNo)
	if orderevent, err = G_OrderMgr.queryOrderEvent(orderno, eventno); err == nil {
		if bytes, err = common.BuildResponse(0, "success", orderevent); err == nil {
			resp.Write(bytes)
		}
	} else {
		if bytes, err = common.BuildResponse(-1, "error", "查询事件异常"); err == nil {
			resp.Write(bytes)
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}
func handleOrderCancelTaxSaveStep(resp http.ResponseWriter, req *http.Request) {
	var (
		err          error
		bytes        []byte
		orderEvtStr  string
		orderevent   *common.OrderEvent
		order        *common.Order
		ordersts     string
		ordernextsts string
		ordertyp     string
		orderno      string
		// rolelimit     *common.RoleLimits
	)
	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	orderEvtStr = req.PostForm.Get("ordereventinfo")

	if err = json.Unmarshal([]byte(orderEvtStr), &orderevent); err != nil {
		goto ERR
	}
	order, _ = G_OrderMgr.getOrderbyNo(orderevent.OrderNo)
	// fmt.Println(clueNo)
	orderno = orderevent.OrderNo
	ordersts = order.OrderStatus
	ordertyp = order.OrderType

	if err = G_OrderMgr.saveOrderEvent(orderevent); err == nil {

		if ordertyp == "注册" {
			ordernextsts = common.GetNextBussOrderSts(ordersts)
			// fmt.Println(orderno, ordernextsts)
			G_OrderMgr.updOrderSts(orderno, ordernextsts)
		}
		if ordertyp == "变更" {
			ordernextsts = common.GetNextChangeOrderSts(ordersts)
			// fmt.Println(orderno, ordernextsts)
			G_OrderMgr.updOrderSts(orderno, ordernextsts)
		}
		if ordertyp == "注销" {
			ordernextsts = common.GetNextCacncelBusOrderSts(ordersts)
			// fmt.Println(orderno, ordernextsts)
			G_OrderMgr.updOrderSts(orderno, ordernextsts)
		}

		if bytes, err = common.BuildResponse(0, "success", orderevent); err == nil {
			resp.Write(bytes)
		}
	} else {
		if bytes, err = common.BuildResponse(-1, "error", "新增任务异常"); err == nil {
			resp.Write(bytes)
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleOrderEventSaveStep(resp http.ResponseWriter, req *http.Request) {
	var (
		err          error
		bytes        []byte
		orderEvtStr  string
		orderevent   *common.OrderEvent
		order        *common.Order
		ordersts     string
		ordernextsts string
		ordertyp     string
		orderno      string
		taxnextsts   string
		// rolelimit     *common.RoleLimits
	)
	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	orderEvtStr = req.PostForm.Get("ordereventinfo")

	if err = json.Unmarshal([]byte(orderEvtStr), &orderevent); err != nil {
		goto ERR
	}
	order, _ = G_OrderMgr.getOrderbyNo(orderevent.OrderNo)
	// fmt.Println(clueNo)
	orderno = orderevent.OrderNo
	ordersts = order.OrderStatus
	ordertyp = order.OrderType

	if err = G_OrderMgr.saveOrderEvent(orderevent); err == nil {

		if ordertyp == "注册" {
			ordernextsts = common.GetNextBussOrderSts(ordersts)
			// fmt.Println(orderno, ordernextsts)
			G_OrderMgr.updOrderSts(orderno, ordernextsts)
		}
		if ordertyp == "变更" {
			ordernextsts = common.GetNextChangeOrderSts(ordersts)
			// fmt.Println(orderno, ordernextsts)
			G_OrderMgr.updOrderSts(orderno, ordernextsts)
		}
		if ordertyp == "注销" {
			//如果是税务注销流程，只更新订单的税务状态，不更新流程状态
			if orderevent.EventType2 == "税务注销" {
				taxnextsts = common.GetCANCELBUSTAXSTS(order.TaxStatus)
				G_OrderMgr.updTaxSts(orderno, taxnextsts)
			} else {
				ordernextsts = common.GetNextCacncelBusOrderSts(ordersts)
				// fmt.Println(orderno, ordernextsts)
				G_OrderMgr.updOrderSts(orderno, ordernextsts)
			}
		}

		if bytes, err = common.BuildResponse(0, "success", orderevent); err == nil {
			resp.Write(bytes)
		}
	} else {
		if bytes, err = common.BuildResponse(-1, "error", "新增任务异常"); err == nil {
			resp.Write(bytes)
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleOrderEventSave(resp http.ResponseWriter, req *http.Request) {
	var (
		err         error
		bytes       []byte
		orderEvtStr string
		orderevent  *common.OrderEvent

		// rolelimit     *common.RoleLimits
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	orderEvtStr = req.PostForm.Get("ordereventinfo")

	if err = json.Unmarshal([]byte(orderEvtStr), &orderevent); err != nil {
		goto ERR
	}
	// fmt.Println(clueNo)
	if orderevent.OrderNo == "" {
		if bytes, err = common.BuildResponse(-1, "error", "OrderNo不能为空，订单任务为订单号，客户任务为客户号！"); err == nil {
			resp.Write(bytes)
		}
		return
	}
	if err = G_OrderMgr.saveOrderEvent(orderevent); err == nil {
		if bytes, err = common.BuildResponse(0, "success", orderevent); err == nil {
			resp.Write(bytes)
		}
	} else {
		if bytes, err = common.BuildResponse(-1, "error", "新增任务异常"); err == nil {
			resp.Write(bytes)
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}
func handleOrderdel(resp http.ResponseWriter, req *http.Request) {
	var (
		err     error
		bytes   []byte
		orderno string

		// rolelimit     *common.RoleLimits
	)

	query := req.URL.Query()
	orderno = query.Get("orderno")
	// fmt.Println(clueNo)

	// fmt.Println(clueinfo)
	if err = G_OrderMgr.delOrder(orderno); err == nil {
		if bytes, err = common.BuildResponse(0, "success", "删除订单成功"); err == nil {
			resp.Write(bytes)
		}
	} else {
		goto ERR
	}
	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func (orderMgr *OrderMgr) updTaxSts(orderNo string, taxstatus string) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		filter   *common.OrderNoFilter
		doccount int64
		// update *common.HostInfo
	)

	filter = &common.OrderNoFilter{
		OrderNo: orderNo,
	}

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), filter, &options.CountOptions{}); err != nil {
		return
	}

	if doccount > 0 {
		//记录公示公告日期

		orderMgr.OrderColl.FindOneAndUpdate(context.TODO(), filter, bson.M{"$set": bson.M{"taxStatus": taxstatus}})

	}

	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (orderMgr *OrderMgr) updOrderSts(orderNo string, orderstatus string) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		filter   *common.OrderNoFilter
		doccount int64
		// update *common.HostInfo
	)

	filter = &common.OrderNoFilter{
		OrderNo: orderNo,
	}

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), filter, &options.CountOptions{}); err != nil {
		return
	}

	if doccount > 0 {
		//记录公示公告日期
		if orderstatus == "公示公告" {
			orderMgr.OrderColl.FindOneAndUpdate(context.TODO(), filter, bson.M{"$set": bson.M{"orderStatus": orderstatus, "publicAnnDate": common.BuildDateTodayStr2()}})
		} else {
			orderMgr.OrderColl.FindOneAndUpdate(context.TODO(), filter, bson.M{"$set": bson.M{"orderStatus": orderstatus}})
		}
	}

	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (orderMgr *OrderMgr) delOrder(orderNo string) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		filter *common.OrderNoFilter
		// update *common.HostInfo
	)

	filter = &common.OrderNoFilter{
		OrderNo: orderNo,
	}

	_, err = orderMgr.OrderColl.DeleteOne(context.TODO(), filter, &options.DeleteOptions{})

	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func InitOrderMgr() (err error) {

	G_OrderMgr = &OrderMgr{
		client:         G_MongoMgr.client,
		OrderColl:      G_MongoMgr.MongdbConnect.Collection("order"),
		OrderEventColl: G_MongoMgr.MongdbConnect.Collection("orderevent"),
	}

	return
}

func handleOrderEventqueryall(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entclueinfo *common.EntClue
		querySet        []bson.M
		skipParam       string
		limitParam      string
		skip            int
		limit           int
		ordereventinfos []*common.OrderEvent
		countorderevent int64
		// rolelimit     *common.RoleLimits

		queryBson bson.M

		ordereventtype      string
		orderno             string
		beginordereventdate string
		endordereventdate   string
		companyname         string
		custommgr           string
		eventno             string
		promoter            string
		eventtype           string
		eventstatus         string
		outstaff            string
	)

	query := req.URL.Query()
	orderno = query.Get("orderno")
	eventno = query.Get("eventno")
	skipParam = query.Get("skip")
	limitParam = query.Get("limit")

	companyname = query.Get("companyname")
	ordereventtype = query.Get("ordereventtype")
	custommgr = query.Get("custommgr")

	promoter = query.Get("promoter")
	eventtype = query.Get("eventtype")
	eventstatus = query.Get("eventstatus")
	outstaff = query.Get("outstaff")

	beginordereventdate = query.Get("beginorderdate")
	endordereventdate = query.Get("endorderdate")

	if skip, err = strconv.Atoi(skipParam); err != nil {
		skip = 0
	}

	if limit, err = strconv.Atoi(limitParam); err != nil {
		limit = 100
	}

	if ordereventtype != "" {
		qordereventtype := bson.M{"orderEventType": ordereventtype}
		querySet = append(querySet, qordereventtype)
	}
	if orderno != "" {
		qorderno := bson.M{"orderNo": orderno}
		querySet = append(querySet, qorderno)
	}

	if companyname != "" {
		qcompanyname := bson.M{"companyName": bson.M{"$regex": companyname, "$options": "$i"}}
		querySet = append(querySet, qcompanyname)
	}
	if eventno != "" {
		qeventno := bson.M{"eventNo": eventno}
		querySet = append(querySet, qeventno)
	}
	if promoter != "" {
		qpromoter := bson.M{"promoter": promoter}
		querySet = append(querySet, qpromoter)
	}
	if eventtype != "" {
		qorderstatus := bson.M{"eventType": eventtype}
		querySet = append(querySet, qorderstatus)
	}
	if eventstatus != "" {
		qeventstatus := bson.M{"eventStatus": eventstatus}
		querySet = append(querySet, qeventstatus)
	}
	if outstaff != "" {
		qoutstaff := bson.M{"outStaff": outstaff}
		querySet = append(querySet, qoutstaff)
	}
	if custommgr != "" {
		qcustommgr := bson.M{"customMgr": custommgr}
		querySet = append(querySet, qcustommgr)
	}

	if beginordereventdate != "" {
		qbegindate := bson.M{"eventDate": bson.M{"$gte": beginordereventdate}}
		querySet = append(querySet, qbegindate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if endordereventdate != "" {
		qenddate := bson.M{"eventDate": bson.M{"$lte": endordereventdate}}
		querySet = append(querySet, qenddate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	queryBson = bson.M{"$and": querySet}

	ordereventmap := make(map[string]interface{})
	countorderevent, _ = G_OrderMgr.countOrderEventbySet(queryBson)
	// fmt.Println(countclue)

	if ordereventinfos, err = G_OrderMgr.queryOrderEventbySet(queryBson, int64(skip), int64(limit)); err != nil {
		goto ERR
	}
	ordereventmap["ordereventcount"] = countorderevent
	ordereventmap["ordereventinfos"] = ordereventinfos
	if bytes, err = common.BuildResponse(0, "success", ordereventmap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleOrderdownload(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entclueinfo *common.EntClue
		querySet   []bson.M
		orderinfos []*common.Order
		// rolelimit     *common.RoleLimits

		queryBson bson.M

		ordertype       string
		orderno         string
		beginorderdate  string
		endorderdate    string
		companyname     string
		clientele       string
		clientelephone1 string
		orderstatus     string
		agentdone       string
		legalperson     string
		agentaccount    string
		clueno          string
		custommgr       string
		channeltype     string
		saleday         string
		salemon         string
		outfile         string
		f               *xlsx.File
		row             *xlsx.Row
		x               *common.Order
	)

	query := req.URL.Query()
	ordertype = query.Get("ordertype")
	orderno = query.Get("orderno")

	companyname = query.Get("companyname")
	clientele = query.Get("clientele")
	clientelephone1 = query.Get("clientelephone1")
	orderstatus = query.Get("orderstatus")
	agentdone = query.Get("agentdone")
	legalperson = query.Get("legalperson")
	agentaccount = query.Get("agentaccount")
	clueno = query.Get("clueno")
	custommgr = query.Get("custommgr")
	channeltype = query.Get("channeltype")
	beginorderdate = query.Get("beginorderdate")
	endorderdate = query.Get("endorderdate")
	saleday = query.Get("saleday")
	salemon = query.Get("salemon")

	if saleday != "" {
		q_cluePhone := bson.M{"orderNo": bson.M{"$regex": common.BuildDateTodayStr(), "$options": "$i"}}
		querySet = append(querySet, q_cluePhone)
	}

	//20201212====2012
	if salemon != "" {
		q_cluePhone := bson.M{"orderNo": bson.M{"$regex": common.BuildDateTodayMonStr(), "$options": "$i"}}
		querySet = append(querySet, q_cluePhone)
	}

	if ordertype != "" {
		qordertype := bson.M{"orderType": ordertype}
		querySet = append(querySet, qordertype)
	}
	if orderno != "" {
		qorderno := bson.M{"orderNo": orderno}
		querySet = append(querySet, qorderno)
	}

	if companyname != "" {
		qcompanyname := bson.M{"companyName": bson.M{"$regex": companyname, "$options": "$i"}}
		querySet = append(querySet, qcompanyname)
	}
	if clientele != "" {
		qclientele := bson.M{"clientele": clientele}
		querySet = append(querySet, qclientele)
	}
	if clientelephone1 != "" {
		qclientelephone1 := bson.M{"clientelePhone1": clientelephone1}
		querySet = append(querySet, qclientelephone1)
	}
	if orderstatus != "" {
		qorderstatus := bson.M{"orderStatus": orderstatus}
		querySet = append(querySet, qorderstatus)
	}
	if agentdone != "" {
		qagentdone := bson.M{"agentDone": agentdone}
		querySet = append(querySet, qagentdone)
	}
	if legalperson != "" {
		qlegalperson := bson.M{"legalPerson": legalperson}
		querySet = append(querySet, qlegalperson)
	}
	if agentaccount != "" {
		qagentaccount := bson.M{"agentAccount": agentaccount}
		querySet = append(querySet, qagentaccount)
	}
	if clueno != "" {
		qclueno := bson.M{"clueNo": clueno}
		querySet = append(querySet, qclueno)
	}

	if channeltype != "" {
		qchanneltype := bson.M{"channelType": channeltype}
		querySet = append(querySet, qchanneltype)
	}

	if custommgr != "" {
		qcustommgr := bson.M{"customMgr": custommgr}
		querySet = append(querySet, qcustommgr)
	}

	if beginorderdate != "" {
		qbegindate := bson.M{"orderDate": bson.M{"$gte": beginorderdate}}
		querySet = append(querySet, qbegindate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if endorderdate != "" {
		qenddate := bson.M{"orderDate": bson.M{"$lte": endorderdate}}
		querySet = append(querySet, qenddate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	queryBson = bson.M{"$and": querySet}

	if orderinfos, err = G_OrderMgr.queryDownloadOrderbySet(queryBson); err != nil {
		// goto ERR
	}

	outfile = "./downloadfile/order" + common.BuildDateTodayStr4() + ".xlsx"
	f = xlsx.NewFile()
	sheet, _ := f.AddSheet("clue")
	for idx, _ := range orderinfos {
		// fmt.Println(idx)
		//写表头
		// fmt.Println(1111 + idx)
		if idx == 0 {
			// fmt.Println(idx)
			x = orderinfos[idx]
			row = sheet.AddRow()
			// reflect.ValueOf(custominfo)
			// v := reflect.ValueOf(&custominfo)
			// n := reflect.ValueOf(&custominfo).NumField()
			t := reflect.TypeOf(x)
			if t.Kind() == reflect.Ptr {
				t = t.Elem()
			}
			// fmt.Println(t.Kind())
			if t.Kind() != reflect.Struct {
				fmt.Println("Check type error not Struct")
				return
			}
			n := t.NumField()
			for i := 0; i < n; i = i + 1 {
				cell := row.AddCell()
				cell.SetValue(t.Field(i).Tag.Get("uname"))
			}
		}

		row = sheet.AddRow()
		x = orderinfos[idx]
		row.WriteStruct(x, -1)
	}
	if err = f.Save(outfile); err != nil {
		// goto ERR
	}

	cluemap := make(map[string]interface{})

	cluemap["filepath"] = G_config.FileUrl + ":" + strconv.Itoa(G_config.ApiPort) + "/downloadfile/order" + common.BuildDateTodayStr4() + ".xlsx"

	if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleOrderqueryall(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entclueinfo *common.EntClue
		querySet   []bson.M
		skipParam  string
		limitParam string
		skip       int
		limit      int
		orderinfos []*common.Order
		countorder int64
		// rolelimit     *common.RoleLimits

		queryBson bson.M

		ordertype       string
		orderno         string
		beginorderdate  string
		endorderdate    string
		companyname     string
		clientele       string
		clientelephone1 string
		orderstatus     string
		agentdone       string
		legalperson     string
		agentaccount    string
		clueno          string
		custommgr       string
		channeltype     string
		saleday         string
		salemon         string
	)

	query := req.URL.Query()
	ordertype = query.Get("ordertype")
	orderno = query.Get("orderno")
	skipParam = query.Get("skip")
	limitParam = query.Get("limit")

	companyname = query.Get("companyname")
	clientele = query.Get("clientele")
	clientelephone1 = query.Get("clientelephone1")
	orderstatus = query.Get("orderstatus")
	agentdone = query.Get("agentdone")
	legalperson = query.Get("legalperson")
	agentaccount = query.Get("agentaccount")
	clueno = query.Get("clueno")
	custommgr = query.Get("custommgr")
	channeltype = query.Get("channeltype")
	beginorderdate = query.Get("beginorderdate")
	endorderdate = query.Get("endorderdate")
	saleday = query.Get("saleday")
	salemon = query.Get("salemon")

	if skip, err = strconv.Atoi(skipParam); err != nil {
		skip = 0
	}

	if limit, err = strconv.Atoi(limitParam); err != nil {
		limit = 100
	}

	if saleday != "" {
		q_cluePhone := bson.M{"orderNo": bson.M{"$regex": common.BuildDateTodayStr(), "$options": "$i"}}
		querySet = append(querySet, q_cluePhone)
	}

	//20201212====2012
	if salemon != "" {
		q_cluePhone := bson.M{"orderNo": bson.M{"$regex": common.BuildDateTodayMonStr(), "$options": "$i"}}
		querySet = append(querySet, q_cluePhone)
	}

	if ordertype != "" {
		qordertype := bson.M{"orderType": ordertype}
		querySet = append(querySet, qordertype)
	}
	if orderno != "" {
		qorderno := bson.M{"orderNo": orderno}
		querySet = append(querySet, qorderno)
	}

	if companyname != "" {
		qcompanyname := bson.M{"companyName": bson.M{"$regex": companyname, "$options": "$i"}}
		querySet = append(querySet, qcompanyname)
	}
	if clientele != "" {
		qclientele := bson.M{"clientele": clientele}
		querySet = append(querySet, qclientele)
	}
	if clientelephone1 != "" {
		qclientelephone1 := bson.M{"clientelePhone1": clientelephone1}
		querySet = append(querySet, qclientelephone1)
	}
	if orderstatus != "" {
		qorderstatus := bson.M{"orderStatus": orderstatus}
		querySet = append(querySet, qorderstatus)
	}
	if agentdone != "" {
		qagentdone := bson.M{"agentDone": agentdone}
		querySet = append(querySet, qagentdone)
	}
	if legalperson != "" {
		qlegalperson := bson.M{"legalPerson": legalperson}
		querySet = append(querySet, qlegalperson)
	}
	if agentaccount != "" {
		qagentaccount := bson.M{"agentAccount": agentaccount}
		querySet = append(querySet, qagentaccount)
	}
	if clueno != "" {
		qclueno := bson.M{"clueNo": clueno}
		querySet = append(querySet, qclueno)
	}

	if channeltype != "" {
		qchanneltype := bson.M{"channelType": channeltype}
		querySet = append(querySet, qchanneltype)
	}

	if custommgr != "" {
		qcustommgr := bson.M{"customMgr": custommgr}
		querySet = append(querySet, qcustommgr)
	}

	if beginorderdate != "" {
		qbegindate := bson.M{"orderDate": bson.M{"$gte": beginorderdate}}
		querySet = append(querySet, qbegindate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if endorderdate != "" {
		qenddate := bson.M{"orderDate": bson.M{"$lte": endorderdate}}
		querySet = append(querySet, qenddate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	queryBson = bson.M{"$and": querySet}

	ordermap := make(map[string]interface{})
	countorder, _ = G_OrderMgr.countOrderbySet(queryBson)
	// fmt.Println(countclue)

	if orderinfos, err = G_OrderMgr.queryOrderbySet(queryBson, int64(skip), int64(limit)); err != nil {
		goto ERR
	}
	ordermap["ordercount"] = countorder
	ordermap["orderinfos"] = orderinfos
	if bytes, err = common.BuildResponse(0, "success", ordermap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func (orderMgr *OrderMgr) getOrderbyNo(orderno string) (order *common.Order, err error) {

	// fmt.Println(orderno)
	orderMgr.OrderColl.FindOne(context.TODO(), bson.M{"orderNo": orderno}).Decode(&order)

	return
}

func (orderMgr *OrderMgr) queryOrderEventbySet(setElements bson.M, skip int64, limit int64) (orderevents []*common.OrderEvent, err error) {

	var (
		// resultOne *mongo.InsertOneResult
		cursor         *mongo.Cursor
		ordereventinfo *common.OrderEvent
		findopt        *options.FindOptions
		ctx            context.Context
		orderSort      *common.SortById
		// update *common.HostInfo
	)

	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	findopt = &options.FindOptions{}
	orderSort = &common.SortById{
		SortOrder: -1,
	}
	findopt.SetSort(orderSort)

	if limit > 0 && skip >= 0 {
		findopt.SetLimit(limit)
		findopt.SetSkip(limit * skip)

	} else {
		return
	}
	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)
		cursor, err = orderMgr.OrderEventColl.Find(context.TODO(), bson.M{}, findopt)
	} else {
		// fmt.Println(1)
		cursor, err = orderMgr.OrderEventColl.Find(context.TODO(), setElements, findopt)
	}
	defer cursor.Close(ctx)

	for cursor.Next(ctx) {
		ordereventinfo = &common.OrderEvent{}
		if err = cursor.Decode(ordereventinfo); err != nil {
			continue
		}
		orderevents = append(orderevents, ordereventinfo)
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (orderMgr *OrderMgr) queryDownloadOrderbySet(setElements bson.M) (orders []*common.Order, err error) {

	var (
		// resultOne *mongo.InsertOneResult
		cursor    *mongo.Cursor
		orderinfo *common.Order
		findopt   *options.FindOptions
		ctx       context.Context
		orderSort *common.SortById
		// update *common.HostInfo
	)

	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	findopt = &options.FindOptions{}
	orderSort = &common.SortById{
		SortOrder: -1,
	}
	findopt.SetSort(orderSort)
	findopt.SetBatchSize(3000)

	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)
		cursor, err = orderMgr.OrderColl.Find(context.TODO(), bson.M{}, findopt)
	} else {
		// fmt.Println(1)
		cursor, err = orderMgr.OrderColl.Find(context.TODO(), setElements, findopt)
	}
	defer cursor.Close(ctx)

	for cursor.Next(ctx) {
		orderinfo = &common.Order{}
		if err = cursor.Decode(orderinfo); err != nil {
			continue
		}
		orderinfo.LegalPhone = ""
		orderinfo.ClientelePhone1 = ""
		orderinfo.ClientelePhone2 = ""
		orders = append(orders, orderinfo)
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (orderMgr *OrderMgr) queryOrderbySet(setElements bson.M, skip int64, limit int64) (orders []*common.Order, err error) {

	var (
		// resultOne *mongo.InsertOneResult
		cursor    *mongo.Cursor
		orderinfo *common.Order
		findopt   *options.FindOptions
		ctx       context.Context
		orderSort *common.SortById
		// update *common.HostInfo
	)

	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	findopt = &options.FindOptions{}
	orderSort = &common.SortById{
		SortOrder: -1,
	}
	findopt.SetSort(orderSort)

	if limit > 0 && skip >= 0 {
		findopt.SetLimit(limit)
		findopt.SetSkip(limit * skip)

	} else {
		return
	}
	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)
		cursor, err = orderMgr.OrderColl.Find(context.TODO(), bson.M{}, findopt)
	} else {
		// fmt.Println(1)
		cursor, err = orderMgr.OrderColl.Find(context.TODO(), setElements, findopt)
	}
	defer cursor.Close(ctx)

	for cursor.Next(ctx) {
		orderinfo = &common.Order{}
		if err = cursor.Decode(orderinfo); err != nil {
			continue
		}
		orders = append(orders, orderinfo)
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (orderMgr *OrderMgr) countOrderbySet(setElements bson.M) (countClue int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)
	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)
		countClue, err = orderMgr.OrderColl.CountDocuments(ctx, bson.M{})
	} else {
		// fmt.Println(1)
		countClue, err = orderMgr.OrderColl.CountDocuments(ctx, setElements)
	}
	return
}

func (orderMgr *OrderMgr) countOrderEventbySet(setElements bson.M) (countClue int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)
	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)
		countClue, err = orderMgr.OrderEventColl.CountDocuments(ctx, bson.M{})
	} else {
		// fmt.Println(1)
		countClue, err = orderMgr.OrderEventColl.CountDocuments(ctx, setElements)
	}
	return
}

func handleOrderSaveStep(resp http.ResponseWriter, req *http.Request) {
	var (
		err          error
		bytes        []byte
		orderinfo    *common.Order
		orderinfostr string
		ordertyp     string
		ordernextsts string
		ordersts     string
		// rolelimit     *common.RoleLimits
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	orderinfostr = req.PostForm.Get("orderinfo")
	if err = json.Unmarshal([]byte(orderinfostr), &orderinfo); err != nil {
		goto ERR
	}
	ordersts = orderinfo.OrderStatus
	ordertyp = orderinfo.OrderType
	if orderinfo.OrderNo != "" && orderinfo.OrderType != "" {
		if ordertyp == "注册" {
			ordernextsts = common.GetNextBussOrderSts(ordersts)
			// fmt.Println(orderno, ordernextsts)
		}
		if ordertyp == "变更" {
			ordernextsts = common.GetNextChangeOrderSts(ordersts)
			// fmt.Println(orderno, ordernextsts)
		}
		if ordertyp == "注销" {
			ordernextsts = common.GetNextCacncelBusOrderSts(ordersts)
			// fmt.Println(orderno, ordernextsts)
		}
		orderinfo.OrderStatus = ordernextsts
		if err = G_OrderMgr.saveOrder(orderinfo); err == nil {
			if bytes, err = common.BuildResponse(0, "success", orderinfo); err == nil {
				resp.Write(bytes)
			}
		} else {
			if bytes, err = common.BuildResponse(-1, "error", "订单更新异常"); err == nil {
				resp.Write(bytes)
			}
		}
	} else {
		if bytes, err = common.BuildResponse(-1, "error", "订单号、订单类型不能为空"); err == nil {
			resp.Write(bytes)
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleOrderSave(resp http.ResponseWriter, req *http.Request) {
	var (
		err          error
		bytes        []byte
		orderinfo    *common.Order
		orderinfostr string
		orderSum     int64
		orderNo      string

		// rolelimit     *common.RoleLimits
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	orderinfostr = req.PostForm.Get("orderinfo")

	if err = json.Unmarshal([]byte(orderinfostr), &orderinfo); err != nil {
		goto ERR
	}

	if orderinfo.OrderNo == "" {
		if orderinfo.OrderType != "" {

			orderSum, _ = G_OrderMgr.getOrderSumToday()

			if orderinfo.OrderType == "注册" {
				orderNo = "ZC" + common.BuildDateTodayStr() + strconv.FormatInt(orderSum+1, 10)
			} else if orderinfo.OrderType == "迁入" {
				orderNo = "QR" + common.BuildDateTodayStr() + strconv.FormatInt(orderSum+1, 10)
			} else if orderinfo.OrderType == "变更" {
				orderNo = "BG" + common.BuildDateTodayStr() + strconv.FormatInt(orderSum+1, 10)
			} else if orderinfo.OrderType == "注销" {
				orderNo = "ZX" + common.BuildDateTodayStr() + strconv.FormatInt(orderSum+1, 10)
			} else if orderinfo.OrderType == "其他" {
				orderNo = "QT" + common.BuildDateTodayStr() + strconv.FormatInt(orderSum+1, 10)
			} else if orderinfo.OrderType == "商标" {
				orderNo = "SB" + common.BuildDateTodayStr() + strconv.FormatInt(orderSum+1, 10)
			} else if orderinfo.OrderType == "建筑资质" {
				orderNo = "ZZ" + common.BuildDateTodayStr() + strconv.FormatInt(orderSum+1, 10)
			}

			orderinfo.OrderNo = orderNo
			orderinfo.CreateTime = common.BuildDateTodayStr2()
			//同步更新线索库的状态为已成单
			if orderNo != "" {
				G_clueMgr.updClueV(orderinfo.ClueNo)
			}
		} else {
			if bytes, err = common.BuildResponse(-1, "error", "订单类型不可为空"); err == nil {
				resp.Write(bytes)
			}
		}
	}
	// fmt.Println(clueinfo)
	if err = G_OrderMgr.saveOrder(orderinfo); err == nil {
		if bytes, err = common.BuildResponse(0, "success", orderinfo); err == nil {
			resp.Write(bytes)
		}
	} else {
		if bytes, err = common.BuildResponse(-1, "error", "新增订单异常"); err == nil {
			resp.Write(bytes)
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleUpdStsById(resp http.ResponseWriter, req *http.Request) {

	var (
		err         error
		bytes       []byte
		orderno     string
		orderstatus string
	)

	query := req.URL.Query()
	orderno = query.Get("orderno")
	orderstatus = query.Get("orderstatus")

	if err = G_OrderMgr.updOrderSts(orderno, orderstatus); err == nil {
		if bytes, err = common.BuildResponse(0, "success", "修改订单状态成功"); err == nil {
			resp.Write(bytes)
		}
	} else {
		goto ERR
	}
	return

ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
	// fmt.Println(clueNo)

}

func (orderMgr *OrderMgr) updOrderServerAllDate(orderNo string, ordersvrbegdate string, ordersvrenddate string) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		filter   *common.OrderIdFilter
		doccount int64
		// update *common.HostInfo
	)

	filter = &common.OrderIdFilter{
		OrderNo: orderNo,
	}

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), filter, &options.CountOptions{}); err != nil {
		return
	}
	if doccount > 0 {
		orderMgr.OrderColl.FindOneAndUpdate(context.TODO(), filter, bson.M{"$set": bson.M{"agentFeeEndDate": ordersvrenddate, "agentBeginDate": ordersvrbegdate}})
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (orderMgr *OrderMgr) saveOrder(orderInfo *common.Order) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		filter   *common.OrderIdFilter
		doccount int64
		// update *common.HostInfo
	)
	orderInfo.CreateTime = common.BuildDateTodayStr2()

	filter = &common.OrderIdFilter{
		OrderNo: orderInfo.OrderNo,
	}

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), filter, &options.CountOptions{}); err != nil {
		return
	}

	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))

	if doccount > 0 {
		orderMgr.OrderColl.UpdateOne(context.TODO(), filter, bson.M{"$set": orderInfo})
	} else {
		orderMgr.OrderColl.InsertOne(context.TODO(), orderInfo)
	}

	return
}
func (orderMgr *OrderMgr) getOrderSumToday() (doccount int64, err error) {

	if doccount, err = orderMgr.OrderColl.CountDocuments(context.TODO(), bson.M{"orderNo": bson.M{"$regex": common.BuildDateTodayStr(), "$options": "$i"}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}

	return
}
